package org.opens.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Autowired
    private TaskExecutor taskExecutor;

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("hello-");
        /**
         * 设置多线程拒绝策略:
         *      1. ThreadPoolExecutor.CallerRunsPolicy()        由调用线程处理该任务, 也就是说这个异步任务在调用线程中执行;
         *      2. ThreadPoolExecutor.AbortPolicy()             丢弃任务并抛出RejectedExecutionException异常;
         *      3. ThreadPoolExecutor.DiscardPolicy()           丢弃被拒绝的任务;
         *      4. ThreadPoolExecutor.DiscardOldestPolicy()     丢弃队列最前面的任务, 然后重新尝试执行这个任务, 重复这个过程;
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
